package run.iget.framework.common.serializer;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.Date;

@NoArgsConstructor
@AllArgsConstructor
public class DateToStringSerializer extends JsonSerializer<Date> implements ContextualSerializer {

    /**
     * 字段注解
     */
    private JsonFormat jsonFormat;

    /**
     * 默认序列化yyyy-MM-dd HH:mm:ss
     * 若存在@JsonFormat(pattern = "xxx") 则根据具体其表达式序列化
     */
    @Override
    public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            return;
        }
        String pattern = jsonFormat == null ? DatePattern.NORM_DATETIME_PATTERN : jsonFormat.pattern();
        gen.writeString(DateUtil.format(value, pattern));
    }

    /**
     * 通过字段已知的上下文信息定制 JsonSerializer
     * 若字段上存在@JsonFormat(pattern = "xxx") 则根据上面的表达式进行序列化
     */
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
        JsonFormat ann = property.getAnnotation(JsonFormat.class);
        if (ann != null) {
            return new DateToStringSerializer(ann);
        }
        return this;
    }
}
